package zooin.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class EditMemberJoin extends Activity {
	public static Activity activity;
	protected TextView getID;
	protected EditText getNick;
	protected EditText getDevName;
	private EditText PWD;
	private TextView textID;
	private EditText editNick;
	private EditText editPWD;
	private EditText editPWD2;
	private EditText editDev;
	private ImageButton nickBtn;
	private ImageButton editBtn;
	private ImageButton cancelBtn;
	public function fc = new function();
	public static String INTENT_VAL ="";
	private TextView pId;
	private String thisIP,thisM;
	private SharedPreferences pref =null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_member_join);
        
        SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
	        String pId 			= prefs.getString("pId", "");
	         thisIP 		= prefs.getString("thisIP", "");
	         thisM 				= prefs.getString("thisM", "");

        getID = (TextView)findViewById(R.id.textViewID);
      //getID.setFocusableInTouchMode(false);
        getID.setText(pId);
        
  //      intenter();
       
        getNick = (EditText)findViewById(R.id.editNick);
        getDevName = (EditText)findViewById(R.id.editDevice);
        
        String html; 
	     html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=2005&userid="+pId+"&deviceType="+thisM,this);
	     String retCode = html.split("ú")[0].trim();
	     String setHtml = html.split("ú")[1].trim();
	     	getNick.setText(html.split("")[2].trim());
		 final String deviceIdx = html.split("")[3].trim();
	     String deviceName = html.split("")[4].trim();
		     deviceName = deviceName.split("ú")[0].trim();
		     getDevName.setText(deviceName);
	     
    	nickBtn = (ImageButton) findViewById(R.id.editBtnSearchNick);
    	editBtn = (ImageButton) findViewById(R.id.btnEditOk);
    	cancelBtn = (ImageButton) findViewById(R.id.btnCancel);    	
    	
    	
        //닉네임 검색버튼
    	nickBtn.setOnClickListener(new View.OnClickListener(){
  		   @Override
  		   public void onClick(View arg0) {
  			   //닉네임 검색
  			  checkNick();
  		   }
          });
      //수정버튼
    	editBtn.setOnClickListener(new View.OnClickListener(){
  		   @Override
  		   public void onClick(View arg0) {
  			 //Toast.makeText(EditMemberJoin.this, "수정버튼", Toast.LENGTH_SHORT).show();
  			  confirm(deviceIdx);
  		   }
          });
       //취소버튼
    	cancelBtn.setOnClickListener(new View.OnClickListener(){
   		   @Override
   		   public void onClick(View arg0) {
   			   EditMemberJoin.this.finish();
   		   }
           });
    }
    

 //로그인 처리
    public void confirm(String devidx){
	    SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
	    	thisIP 		= prefs.getString("thisIP", "");
    
    	textID 		=	(TextView) findViewById(R.id.textViewID);	String UserID	= textID.getText().toString();
	    PWD 		=	(EditText) findViewById(R.id.PWD);			String orgPWD	= PWD.getText().toString();
	    editPWD		=	(EditText) findViewById(R.id.editPWD);		String UserPWD	= editPWD.getText().toString();
	    editPWD2	=	(EditText) findViewById(R.id.editPWD2);		String UserPWD2	= editPWD2.getText().toString();
	   // editNick 	= 	(EditText) findViewById(R.id.editNick);		String UserNick	= editNick.getText().toString();
	    editDev		=	(EditText) findViewById(R.id.editDevice);	String DevName	= editDev.getText().toString();
	    String html;
	    
	    html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=1000&userid="+ UserID +"&userpwd="+orgPWD,this);
    	int htmlValue1 = Integer.parseInt(html.split("ú")[0]);
    	//Toast.makeText(EditMemberJoin.this, "UserID:"+UserID+", orgPWD:"+orgPWD+", htmlValue:"+html, Toast.LENGTH_SHORT).show();
    	//Toast.makeText(EditMemberJoin.this, "idx:"+devidx, Toast.LENGTH_SHORT).show();
    	
    	if( "".equals(orgPWD) || orgPWD == null){
    		Toast.makeText(EditMemberJoin.this, "패스워드를 입력하세요.", Toast.LENGTH_SHORT).show();
    		return ;
    	}
    	if( !UserPWD.equals(UserPWD2)){
    		Toast.makeText(EditMemberJoin.this, "새 암호가 일치하지 않습니다.\n다시 입력하세요.", Toast.LENGTH_SHORT).show();
    		return ;
    	}
    	if(!(htmlValue1 > 0)){
    	    
    		Toast.makeText(EditMemberJoin.this, "패스워드가 틀렸습니다.\n다시 입력해주세요." , Toast.LENGTH_SHORT).show();
    		return ;
    	}
    	if( "".equals(DevName) || DevName == null){
    		Toast.makeText(EditMemberJoin.this, "장치명을 입력하세요.", Toast.LENGTH_SHORT).show();
    		return ; 	   
    	}
    	if( !checkNick()){
    		return ;
    	}else{
    		alertDialog(devidx);
    		//html = fc.DownloadHtml("http://"+fc.IP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=2006&userid="+UserID+"&userpwd="+UserPWD+"&usernick="+UserNick+"&deviceIdx="+devidx+"&deviceName="+DevName);
    		//Toast.makeText(EditMemberJoin.this, "html"+html, Toast.LENGTH_LONG).show();
    		//Toast.makeText(EditMemberJoin.this, "Update ok", Toast.LENGTH_SHORT).show();
    	}
		return ;
    }

    
    public boolean checkNick(){
    	
    	editNick 	= 	(EditText) findViewById(R.id.editNick);		String UserNick = editNick.getText().toString().trim();
	    
	    SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
        	String pName 		= prefs.getString("pName", "").trim();    
        	thisIP 		= prefs.getString("thisIP", "");
        
        String html;
    	boolean retVal = false;

		if(!UserNick.replace(" ", "").equals("") ){			 
	     html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=1006&usernick="+ URLEncoder.encode(UserNick),this);
	     String GetNick = html.split("ú")[0].trim();
	     
	    // Toast.makeText(EditMemberJoin.this, "html : "+html, Toast.LENGTH_SHORT).show();
	     
		// Toast.makeText(EditMemberJoin.this, "pName"+pName, Toast.LENGTH_SHORT).show();
		       if(GetNick.charAt(0) == '1'){

		  		 //Toast.makeText(EditMemberJoin.this, "pName"+pName, Toast.LENGTH_SHORT).show();
		    	   //다른 ID를 사용하세요.a
		    	   if( !UserNick.equals(pName) ){
		    		   Toast.makeText(EditMemberJoin.this, "이미 사용중인 닉네임입니다.\n다른 닉네임을 사용하세요.", Toast.LENGTH_SHORT).show();
		    		   editNick.requestFocus();
		    	   }else{
		    		   Toast.makeText(EditMemberJoin.this, "너의 닉네임이네.", Toast.LENGTH_SHORT).show();
			    	   retVal = true;
		    	   }
		       }else{
		    	   Toast.makeText(EditMemberJoin.this, "닉네임 사용가능 합니다.", Toast.LENGTH_SHORT).show();
		    	   retVal = true;
		       }
	     }
	     else{
	  	   Toast.makeText(EditMemberJoin.this, "닉네임을 입력하세요", Toast.LENGTH_SHORT).show();
	  	   editNick.requestFocus();
	     }
		return retVal;
    }

    private void alertDialog(final String devidx){

	    SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE);
	    	thisIP 		= prefs.getString("thisIP", "");
	    	
    	    AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
    	    alt_bld.setMessage("정말 수정하시겠습니까?").setCancelable(
    	        false).setPositiveButton("네",new DialogInterface.OnClickListener() {
    	        	public void onClick(DialogInterface dialog, int id) {
    	        		// Action for 'Yes' Button
    	        		textID = (TextView) findViewById(R.id.textViewID);
    	        	    String UserID = textID.getText().toString();
    	        	    PWD =  (EditText) findViewById(R.id.PWD);
    	        	    String cUserPWD = PWD.getText().toString();
    	        	    
    	        	    editPWD =  (EditText) findViewById(R.id.editPWD);
    	        	    String UserPWD = editPWD.getText().toString();

    	        	    editNick =  (EditText) findViewById(R.id.editNick);
    	        	    String UserNick = editNick.getText().toString();
    	        		UserNick = UserNick.split("ú")[0];
    	        		
    	        	    editDev =  (EditText) findViewById(R.id.editDevice);
    	        	    String DevName = editDev.getText().toString();
    	        	    DevName = DevName.split("ú")[0];
    	        	    
    	        		String html;
    	        		
    	        		if(UserPWD.replace(" ", "").equals("")){
    	        			UserPWD = cUserPWD;
    	        		}
    	        		
    	        		//업데이트 완료
    	        		pref    = getSharedPreferences("userInfo",Activity.MODE_PRIVATE);
    	        	    SharedPreferences.Editor editor = pref.edit(); 
	    		        editor.putString("pPasswd", UserPWD);
	    		        editor.putString("pName", UserNick);
	    		        editor.putString("pDeviceName", DevName);
    	            	editor.commit();
    	            		
    	        		html = fc.DownloadHtml("http://"+thisIP+"/iptvcast2/extern/zMobile_cmd.php?OPCODE=2006&userid="+UserID+"&userpwd="+UserPWD+"&usernick="+URLEncoder.encode(UserNick)+"&deviceIdx="+devidx+"&deviceName="+URLEncoder.encode(DevName), EditMemberJoin.this);
    	        		html = html.split("ú")[0];
    	        		
    	        		Toast.makeText(EditMemberJoin.this, "수정되었습니다.", Toast.LENGTH_SHORT).show();

    	        		EditMemberJoin.this.finish();
    	        		
    	        	}
    	        }).setNegativeButton("아니오",new DialogInterface.OnClickListener() {
    	        	public void onClick(DialogInterface dialog, int id) {
    	        		// Action for 'NO' Button
    	        		//dialog.cancel();
    	        		EditMemberJoin.this.finish();
    	        	}

    	        });

    	    AlertDialog alert = alt_bld.create();
    	    // Title for AlertDialog
    	    alert.setTitle("회원정보 수정");
    	    // Icon for AlertDialog
    	    alert.setIcon(R.drawable.icon);
    	    alert.show();
    	}
    
    
    @Override
    public void onBackPressed() {
    	EditMemberJoin.this.finish();
    	//alertEnd();
	}
    
}